<script setup lang="ts">
import { regionData, CodeToText } from 'element-china-area-data'
import { ref, watch } from 'vue'
import { AreaItem, AreaData } from '../../../types/chooseArea/index'

// 选中的省市区的值
let province = ref<string>('')
let city = ref<string>('')
let area = ref<string>('')

// 省市区下拉框列表数据
const provinceList = ref<AreaItem[]>(regionData)
let cityList = ref<AreaItem[]>([])
let areaList = ref<AreaItem[]>([])

const emits = defineEmits(['change'])

// 侦听省级下拉的改变
watch(() => province.value, val => {
  city.value = area.value = ''
  if(val){
    cityList.value = provinceList.value.find(item => item.value == province.value)!.children!
  }
})

// 侦听市级下拉的改变
watch(() => city.value, val => {
  area.value = ''
  if(val){
    areaList.value = cityList.value.find(item => item.value == city.value)!.children!
  }
})

// 侦听区级下拉的改变
watch(() => area.value, val => {
  let provinceData : AreaData = {
    value: province.value,
    label: CodeToText[province.value]
  }
  let cityData : AreaData = {
    value: city.value,
    label: CodeToText[city.value] 
  }
  let areaData : AreaData = {
    value: val,
    label: CodeToText[val]
  }
  
  emits('change', { provinceData, cityData, areaData })
})

</script>
<template>
  <div class="">
    <el-select placeholder="请选择省份" v-model="province" clearable>
      <el-option v-for="item in provinceList" :key="item.value" :value="item.value" :label="item.label">{{item.label}}</el-option>
    </el-select>
    <el-select :disabled="!province" style="margin: 0 10px;" placeholder="请选择城市" v-model="city" clearable>
      <el-option v-for="item in cityList" :key="item.value" :value="item.value" :label="item.label">{{item.label}}</el-option>
    </el-select>
    <el-select :disabled="!province || !city" placeholder="请选择区域" v-model="area" clearable>
      <el-option v-for="item in areaList" :key="item.value" :value="item.value" :label="item.label">{{item.label}}</el-option>
    </el-select>
  </div>
</template>
<style lang="scss" scoped>
  
</style>